package com.xposed.aliproxy.pollinglooper.poll;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 线程池控制类
 * Created by Su on 2019/1/4.
 */
public class PollingScheduler {
    private static PollingScheduler sInstance;

    private ScheduledExecutorService mScheduler;
    private ConcurrentHashMap<String, Future> futureMap = new ConcurrentHashMap<>();

    private PollingScheduler() {
        // 单线程池
        mScheduler = Executors.newSingleThreadScheduledExecutor();
    }

    public static synchronized PollingScheduler getInstance() {
        if (sInstance == null) {
            sInstance = new PollingScheduler();
        }
        if (sInstance.mScheduler.isShutdown()) {
            sInstance.mScheduler = Executors.newSingleThreadScheduledExecutor();
        }
        return sInstance;
    }

    /**
     * PollListener轮询回调
     */
    void addScheduleTask(String action, long initialDelay, long period, final PollListener listener) {
        Runnable command = new Runnable() {
            @Override
            public void run() {
                try {
                    listener.onHandlePoll();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        // 固定频率执行任务,不受任务执行时间影响
        Future future = mScheduler.scheduleAtFixedRate(command, initialDelay, period, TimeUnit.MILLISECONDS);
        futureMap.put(action, future);
    }

    /**
     * @param action 停止某个轮询任务
     */
    void clearScheduleTasks(String action) {
        try {
            Future future = futureMap.remove(action);
            future.cancel(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 停止所有轮询任务
     */
    void clearScheduleTasks() {
        mScheduler.shutdownNow();
    }
}
